package com.example.ai.service;

import com.example.ai.dto.question.QuestionRequest;
import com.example.ai.dto.question.QuestionResponse;
import com.example.ai.model.Question;
import com.example.ai.model.User;
import com.example.ai.repository.QuestionRepository;
import com.example.ai.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChatService {

    private final QuestionRepository questionRepository;
    private final UserRepository userRepository;
    private final DeepseekService deepseekService;
    private final QwenService qwenService;

    private QuestionResponse convertToResponse(Question question) {
        return QuestionResponse.builder()
                .id(question.getId())
                .content(question.getContent())
                .answer(question.getAnswer())
                .inputType(question.getInputType())
                .username(question.getUser().getUsername())
                .createdAt(question.getCreatedAt())
                .updatedAt(question.getUpdatedAt())
                .build();
    }

    @Transactional
    public QuestionResponse askQuestion(QuestionRequest request) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found"));

        // 根据选择的模型调用不同的服务
        String aiResponse;
        if ("deepseek".equals(request.getModel())) {
            aiResponse = deepseekService.chat(request.getContent());
        } else {
            aiResponse = qwenService.chat(request.getContent());
        }
        log.info("AI response received for question: {}", request.getContent());

        Question question = new Question();
        question.setUser(user);
        question.setContent(request.getContent());
        question.setAnswer(aiResponse);
        question.setInputType(request.getInputType());
        question = questionRepository.save(question);

        return convertToResponse(question);
    }


} 